using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace ilgolosone.Persistence.NH.Data.Impl
{
    public class NHibernateCreateSchemaOnlyOnceSessionCreator : ISessionCreator
    {
        private static readonly object _locker = new object();
        private readonly Configuration _configuration;
        private readonly ISessionFactory _factory;

        public NHibernateCreateSchemaOnlyOnceSessionCreator()
        {
            lock (_locker)
            {
                _configuration = new Configuration().Configure();
                _factory = _configuration.BuildSessionFactory();
                GenerateSchema();
            }
        }

        public ISession CreateSession()
        {
            return _factory.OpenSession();
        }

        public void GenerateSchema()
        {
            new SchemaExport(_configuration).Create(true, true);
        }
    }
}